﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using QuoteOfTheDay;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace QuoteClient
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            btnGet.Tag = QuoteAction.GET.ToString();
            btnRemove.Tag = QuoteAction.REMOVE.ToString();
            btnAddQuote.Tag = QuoteAction.ADD.ToString();
        }

        private void quoteAction_Click(object sender, EventArgs e)
        {
            TcpClient client = new TcpClient();
            client.Connect(IPAddress.Parse(txtAddress.Text), 55555);

            try
            {
                int bytesRead = 1;
                StringBuilder data = new StringBuilder();
                byte[] buffer = new byte[4096];
                byte[] sendBuffer;

                using (NetworkStream ns = client.GetStream())
                {
                    try
                    {
                        string action = (sender as Button).Tag as string;
                        string message = string.Empty;
                        switch (action)
                        {
                            case "ADD":
                                message = action + "|" + txtNewQuote.Text;
                                break;
                            case "REMOVE":
                                message = action + "|" + txtQuote.Text;
                                break;
                            case "GET":
                                message = action + "|";
                                break;
                        }

                        sendBuffer = Encoding.ASCII.GetBytes(message);
                        ns.Write(sendBuffer, 0, sendBuffer.Length);
                   
                        // start waiting on the response
                        bytesRead = ns.Read(buffer, 0, buffer.Length);
                        data.Append(Encoding.ASCII.GetString(buffer));

                        txtQuote.Text = data.ToString();
                        txtNewQuote.Text = string.Empty;
                    }
                    catch (IOException ioe)
                    {
                        Trace.WriteLine("Error in read: {0}", ioe.ToString());
                    }
                }
            }
            finally
            {
                client.Close();
            }
        }
    }
}
